import getpath
import os
import openpyxl
from openpyxl.drawing.image import Image
from PyQt5 import QtWidgets
import io
from PIL import Image as PILImage
# from typing import Tuple
import time
import config_json
import logging
import re
from sample import SampleICP
import openpyxl
import myglobal
import d6300
import icap
from DlgYanghua import DlgYanghua
# import qimage
from mydb import MyDB_Base
class MyDb(MyDB_Base):
    def __init__(self,mainw):
        super().__init__(mainw)
        self.doublefmt="%.7f"
        self.SampleCls=SampleICP
        self.properties = [
            {"ele":None,"delegate":None,'width':130,'attr': "sampleid",'visible':True,  'header': "id"},
            {"ele":None,"delegate":self.floatEdit,'width':80,'attr': "mass",'visible':True,  'header': "质量"},
            {"ele":None,"delegate":self.floatEdit,'width':80,'attr': "volume",'visible':True,  'header': "体积"},
            {"ele":None,"delegate":self.floatEdit,'width':80,'attr': "xishi",'visible':True,  'header': "稀释倍数"},
            {"ele":None,"delegate":self.editDelegate,'width':80,'attr': "beizhu",'visible':True,  'header': "备注"},
        ]
    def getejff(self):
        if self.ejff==None:
            self.ejff= myglobal.server.getlx_ejff("icp")        
        return self.ejff
        # return "'ICP-AES' in ejff"
        return "charindex('ICP-AES',ejff)!=0"
        return ["ICP-AES"]
    def getdepart(self):
        if self.depart==None:
            self.depart=myglobal.server.getlx_depart("icp")
        return self.depart
        # return ["痕量分析组"]

    def contextMenuEvent(self,event):
        menu = QtWidgets.QMenu(self.mainw)
        allAction = menu.addAction("全部")
        noneAction = menu.addAction("全部不选")
        validAction = menu.addAction("去除无效")
        firstAction= menu.addAction("第一个")
        multiAction = menu.addAction("*0.4")
        multiAction2 = menu.addAction("*0.8")
        multiAction3 = menu.addAction("*2")
        multiAction4 = menu.addAction("*0.5")
        multiAction5 = menu.addAction("*5")
        # copyAction = menu.addAction("复制备注")
        # copyAction2 = menu.addAction("复制体积")
        action = menu.exec_(self.mainw.mapToGlobal(event.pos()))
        if action == noneAction:
            self.mainw.noneChannel()
        elif action == allAction:
            self.mainw.allChannel()
        elif action == validAction:
            self.mainw.validChannel()
        elif action == firstAction:
            self.mainw.firstChannel()
        elif action == multiAction:
            self.massMulti(0.4)
        elif action == multiAction2:
            self.massMulti(0.8)
        elif action == multiAction3:
            self.massMulti(2)
        elif action == multiAction4:
            self.massMulti(.5)
        elif action == multiAction5:
            self.massMulti(5)
    def showColumnMenu(self, pos):
        logging.info("showCloumnMenu")
        logging.info(pos)
        it = self.mainw.ui.tableView_report.columnAt(pos.x())  # 根据鼠标坐标获取列号
        logging.info(it)
        # self.title = ["id", "time", "sampleid", "mass", "volume"]
        # title = self.model2.headerData(it, Qt.Horizontal)
        if self.properties[it]["ele"]!=None:
            menu =QtWidgets.QMenu()
            # self.yanghua)
            menu.addAction("氧化物", lambda val=pos: self.yanghua(val))
            # self.yanghua)
            # menu.addAction("移除", lambda val=pos: self.selectChannel(val))
            pos = self.mainw.ui.tableView_report.horizontalHeader().viewport().mapToGlobal(pos)
            return menu.exec_(pos)
    def yanghua(self, pos):
        logging.info("yanghua")
        logging.info(pos)
        it = self.mainw.ui.tableView_report.columnAt(pos.x())  # 根据鼠标坐标获取列号
        logging.info(it)
        # self.title = ["id", "time", "sampleid", "mass", "volume"]
        one= self.properties[it]#.ele# model2.headerData(it, Qt.Horizontal)
        logging.info(one)
        d = DlgYanghua()
        d.ui.lineEdit_ele.setText(one["ele"][0])#ele
        tit = one["header"].split(' ')[0]
        d.ui.edit_yanghua.setText(tit)
        d.ui.edit_xishu.setText(str(one.get("xishu")))
        r = d.exec_()
        if r == 1:
            self.changeYanghua(
                it, d.ui.lineEdit_ele.text(),d.ui.edit_yanghua.text(), d.ui.edit_xishu.text())
        else:
            pass
    def changeYanghua(self, i, ele,yanghua, xishu):
        logging.info(str(i)+","+yanghua+","+str(xishu))
        config_json.setting["weight"]["ele"]=ele
        self.properties[i]["xishu"] = float(xishu)
        titles = self.properties[i]["header"].split(" ")
        newtitle=" ".join([yanghua, titles[1]])
        self.properties[i]["header"]= newtitle
        self.mainw.chks[i].setText(newtitle)
        self.mainw.refresh_grid2()            
    def clear_layout(self, layout):
        while True:
            child = layout.takeAt(0)
            if child is None:
                break
            else:
                child.widget().deleteLater()
    def init_db(self):
        return True
    def checkBoth(self):
        name = []
        for f in self.properties:
            if f["visible"]:
                logging.info(name)
                if (f["ele"]!=None):
                    if(f["ele"][0] in name):
                        QtWidgets.QMessageBox.information(self.mainw, "", "不能同时选择一个元素的两个通道")
                        return True
                    else:
                        name.append(f["ele"][0])
        return False
    def remove_pingxing(self,a):
        for i in range(len(a)):
            if a[i]=="_":
                return a[:i]        
        return a        
    def checkSingle(self):
        n = len(self.mainw.objects2)
        r={}
        for row_idx in range(n):
            record = self.mainw.objects2[row_idx]
            name=str(record.sampleid)
            if config_json.setting["pingxing"]==1:
                name=self.remove_pingxing(name)
            if re.match(self.mainw.sample_name_pattern,name.strip())!=None:# name.strip()[0:0+2]=="23":
                if r.get(name)!=None:
                    r[name]+=1
                else:
                    r[name]=1
        logging.info(r)
        all=[]
        for k in r.keys():
            if r[k]==1:
                all.append(k)
        if len(all)==0:
            return ""
        else:
            return ",".join(all)        
    # def lims(self):
    #     if self.checkBoth():
    #         return
    #     ffbh = self.mainw.ui.cmb_ffbh.text()
    #     syy = self.mainw.ui.cmb_syy.text()
    #     ysry = self.mainw.ui.cmb_ysry.text()
    #     syyqm = self.mainw.ui.cmb_syyqm.text()
    #     yqbh = config_json.setting["yqbh"]
    #     queren = ""
    #     single=self.checkSingle()
    #     if single!="":
    #         queren = queren+"样品(%s)没有平行样!!!\n" % single 
    #         queren = queren+"\n"
    #     queren = queren+"方法编号(%s)\n" % ffbh
    #     queren = queren+"实验员(%s)\n" % syy
    #     queren = queren+"一审(%s)\n" % ysry
    #     queren = queren+"实验员签名(%s)\n" % syyqm
    #     queren = queren+"仪器编号(%s)\n" % yqbh
    #     logging.info(["ejff",config_json.setting["ejff"]])
    #     ejff= self.mainw.ui.cmb_ff2.text()
    #     ejfxjs= self.mainw.ui.cmb_js2.text()
    #     if config_json.setting["ejff"]==1 and ejff!="" and ejfxjs!="":
    #         queren = queren+"二级方法(%s)\n" % ejff
    #         queren = queren+"二级分析技术(%s)" % ejfxjs
    #     r = QtWidgets.QMessageBox.question(
    #         self.mainw, '输出', queren, QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.Yes)
    #     if r == QtWidgets.QMessageBox.No:
    #         return            
    #     if len(yqbh)>4:
    #         yqbh=yqbh[-4:]
    #     if self.mainw.ui.lineEdit_filename.text() == "":
    #         file_name = yqbh + "_" + myglobal.timestr()
    #     else:
    #         file_name = yqbh+"_"+self.mainw.ui.lineEdit_filename.text()
    #     path = config_json.setting["output_folder"]
    #     filepath = os.path.join(path, file_name)
    #     self.output_xlsx(filepath)
    def output_xlsx(self, filepath):
        n = self.mainw.model2.rowCount()
        if n == 0:
            return
        self.mainw.export_num+=1
        filepath = filepath +"_"+str(self.mainw.export_num)+ ".xlsx"
        # 1. 创建文件对象（指定文件名，模式，编码方式）a模式 为 下次写入在这次的下一行
        wb = openpyxl.Workbook()
        ws = wb.active
        # 3. 构建列表头
        row = ["id", "mass", "volume", "稀释倍数"]
        for f in self.properties:
            if f["visible"] and f.get("ele") != None:
                row.append(f["header"].split(" ")[0])
        row.append("备注")
        ws.append(row)
        row = ["BC", "", "", ""]
        for f in self.properties:
            if f["visible"] and f.get("ele") != None:
                row.append(f["ele"][1])
        row.append("")
        ws.append(row)
        row = ["XS", "", "", ""]
        for f in self.properties:
            if f["visible"] and f.get("ele") != None:
                row.append(f.get("xishu",""))
        row.append("")
        ws.append(row)
        hasBLK = False
        hasBLK_SI = False
        for f in self.properties:
            f["BLK"] = None
            f["BLK_SI"] = None
        for row_idx in range(n):
            record = self.mainw.objects2[row_idx]
            sampleid = str(record.sampleid)
            sampleid = sampleid.strip().upper()
            if sampleid == "BLK":
                for f in self.properties:
                    if f["visible"] and f.get("ele") != None:
                        f["BLK"] = myglobal.myfloat(getattr(record,f["attr"]))
                hasBLK = True
            if sampleid in ["BLK_SI", "BLK-SI"]:
                for f in self.fields:
                    if f["visible"] and f.get("ele") != None:
                        f["BLK_SI"] = myglobal.myfloat(getattr(record,f["attr"]))
                hasBLK_SI = True
        logging.info(["hasBLK", hasBLK, "hasBLK_SI", hasBLK_SI])
        for row_idx in range(n):
            record = self.mainw.model2.getObjectRow(row_idx)
            sampleid = str(record.sampleid).strip()
            sampleid_up = sampleid.upper()
            if sampleid_up in ["BLK_SI","BLK-SI"]:
                row = list(["BLK_SI"])
            else:
                sampleid=self.remove_pingxing(sampleid)
                row = list([sampleid])
            mass=myglobal.myfloat(record.mass)
            mass="%.4f" % mass
            row.append(mass)
            row.append(record.volume)
            row.append(record.xishi)
            for f in self.properties:
                if f["visible"] and f.get("ele") != None:
                    if sampleid_up == "BLK":
                        if hasBLK_SI and f["ele"] == "Si":  # replace with blk_si
                            conc = ""
                        else:
                            conc = myglobal.myfloat(getattr(record,f["attr"]))
                            if conc < 0:
                                conc = ""
                            else:
                                conc = self.doublefmt % conc
                        row.append(conc)
                    elif sampleid_up in ["BLK_SI", "BLK-SI"]:
                        if f["ele"] == "Si":  
                            conc = myglobal.myfloat(getattr(record,f["attr"]))
                            if conc < 0:
                                conc = ""
                            else:
                                conc = self.doublefmt % conc
                        else:
                            conc = ""
                        row.append(conc)
                    else:
                        if hasBLK_SI and f["ele"] == "Si":
                            conc = myglobal.myfloat(getattr(record,f["attr"]))
                            conc = self.doublefmt % conc
                            row.append(conc)
                            pass
                        else:
                            conc = myglobal.myfloat(getattr(record,f["attr"]))
                            conc = self.doublefmt % conc
                            row.append(conc)
            row.append(record.beizhu)
            ws.append(row)
        self.output_append_common(ws)
        for one in self.mainw.appends:
            k=one[0]
            w=one[1]
            l=w.l.text()
            v=w.t.text()
            row = [k+"&" + v,l, "", "", ""]
            ws.append(row)
            config_json.setting["append"]["icp"][k]=[l,v]
        # other stuff
        # self.output_ws2(wb) #beifen
        ws = wb.create_sheet("sheet2")
        hang=self.output_origin(ws)+1
        if config_json.setting["sblx"] =="ajl_pdf":
            from ajlpdf import output_curve
            output_curve(ws,hang)
        elif config_json.setting["sblx"] =="icap":
            icap.output_curve(ws,hang)
        else:#if config_json.setting["sblx"] =="spec":
            from qimage import outputImages
            outputImages(self.mainw.iv.lm.listdata,ws,hang)
        wb.save(filepath)
        self.mainw.ui.textEdit.insertPlainText(filepath + "\n")
        scrollbar = self.mainw.ui.textEdit.verticalScrollBar()
        scrollbar.setSliderPosition(scrollbar.maximum()) 
    def output_origin(self, ws):
        n = self.mainw.model2.rowCount()
        row = ["id", "mass", "volume", "稀释倍数"]
        for f in self.properties:
            if f.get("ele")!=None:
                if f.get("xishu")!=None:
                    row.append(f["ele"][0]+" "+f["ele"][1]+ "\n("+f["header"].split(" ")[0]+" "+str(f["xishu"])+")")
                else:
                    row.append(f["header"])
        ws.append(row)
        ncols=len(row)
        hang=1
        for row_idx in range(n):
            record = self.mainw.model2.getObjectRow(row_idx)
            row = list([record.sampleid])
            row.append(record.mass)
            row.append(record.volume)
            row.append(record.xishi)
            for f in self.properties:
                if f.get("ele")!=None:
                    conc =getattr(record,f["attr"]) #record.value(record.indexOf(f["name"]))
                    row.append(conc)
            ws.append(row)
            hang+=1
        ws.column_dimensions['A'].width = 20
        for i in range(ncols):
            letter=openpyxl.utils.cell.get_column_letter(i+1)
            ws.column_dimensions[letter].width = self.origin_column_w
        return hang        
    def elementWave(self, s):
        wave = re.search(r"\d+(\.\d+)?", s).group()
        # element=re.match("[A-Z][a-z]*",s).group()
        element = re.search(r"[A-Z][a-z]*", s).group()
        # element = s.split(" ")[0]
        return (element, wave)   
    def massMulti(self,xs):
        logging.info("==")
        selections = self.mainw.ui.tableView_report.selectionModel()
        list1 = selections.selectedIndexes()
        treated=[]
        for i in range(len(list1)):
            current = list1[i]
            row = current.row()
            if row in treated:
                pass
            else:
                treated.append(row)
                record = self.mainw.model2.getObjectRow(row)
                mass=myglobal.myfloat(record.mass)
                mass=mass*xs
                m="%0.4f" % mass #保留小数点后4位
                m=float(m)
                record.mass=m
                # vol=myglobal.myfloat(record.volume)
                # logging.info([vol,xs])
                # record.volume=vol*xs*10 #mass
                logging.info([row,mass,m])
                # self.model2.submitAll()
    def getDataDays(self, v):
        filename=config_json.setting['database']
        if config_json.setting["sblx"]=="ajl_pdf":
            from ajlpdf import getDataAndMass
            (data,mass)=getDataAndMass(filename)
            at = 1
            objs=[]
            for at in range(len(data)): 
                if at==0:
                    continue
                sample = {"items": [], "conc": []}
                sample["items"] = data[0][1:]
                for i in range(len(sample["items"])):
                    (ele, wave) = self.elementWave(sample["items"][i])
                    sample["items"][i] = (ele, wave)
                sampleid = data[at][0].replace('\n', '')
                if sampleid=="":
                    continue
                sample["sampleid"] = sampleid
                sample["mass"] = mass[at][0]
                sample["volume"] = mass[at][1]
                logging.info(sampleid)
                sample["conc"] = []
                for one in data[at][1:]:
                    sample["conc"].append(one.split(" ")[0])  # remove %
                objs.append(sample)
                # at += 1
            return self.toObjects(objs)
        elif config_json.setting["sblx"]=="6300":
            data=d6300.getdata(filename)
            return self.toObjects(data)
        elif config_json.setting["sblx"]=="icap":
            ss=icap.getdata(filename)
            if len(ss)>0:
                self.resetProperties(ss[0].items)
            return ss
    def resetProperties(self,items):
        self.properties = [
                    {"ele":None,"delegate":None,'width':30,'attr': "num",'visible':True,  'header': "序号"},
            {"ele":None,"delegate":None,'width':130,'attr': "sampleid",'visible':True,  'header': "id"},
            {"ele":None,"delegate":self.floatEdit,'width':80,'attr': "mass",'visible':True,  'header': "质量"},
            {"ele":None,"delegate":self.floatEdit,'width':80,'attr': "volume",'visible':True,  'header': "体积"},
            {"ele":None,"delegate":self.floatEdit,'width':80,'attr': "xishi",'visible':True,  'header': "稀释倍数"},
            {"ele":None,"delegate":self.editDelegate,'width':80,'attr': "beizhu",'visible':True,  'header': "备注"},
        ]
        v=list(items.keys())
        v.sort()
        logging.info(v)
        for item in v:
            # logging.info([item[0],"CPS" in item[0]])
            if ("Final" in item[0]) or ("CPS" in item[0]) or ("内标" in item[0]):
                one={"ele":item,"delegate":self.m_doubleDeleget,'width':90,'attr': item[0]+"_"+item[1],'visible':False,  'header': item[0]+" "+item[1]}
            else:
                one={"ele":item,"delegate":self.m_doubleDeleget,'width':90,'attr': item[0]+"_"+item[1],'visible':True,  'header': item[0]+" "+item[1]}
            self.properties.append(one)
    def toObjects(self,samples):        
        objs=[]
        num=0
        for one in samples:
            s=SampleICP()
            s.sampleid=one["sampleid"]
            logging.info(s.sampleid)
            s.mass=one["mass"]
            s.volume=one["volume"]
            s.xishi=one.get("xishi","")
            s.items={}
            s.num=num
            for i in range(len(one["items"])): #one in one["items"]:
                s.items[one["items"][i]]=one["conc"][i]
            objs.append(s)
            num+=1
        self.resetProperties(s.items)
        return objs  
def test_getdata():
    fname=os.path.join(getpath.getpath(),"..","data","202401121711.xls")#"6300.xls")
    data=getdata(fname)
    return data              
if __name__ == "__main__":
    test_getdata()